import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:get/get.dart' as GetX;
import 'package:overload_guard/main.dart';
import 'package:overload_guard/main_provider.dart';
import 'package:overload_guard/services/db_service.dart';
import 'package:overload_guard/widgets/dialogs.dart';

class APIService {
  /// 登陆
  static loginToken({required String password, required String phone}) async {
    return await fetch('/login/token',
        method: 'POST',
        data: {"password": password, "phone": phone, "userType": 1});
  }

  /// 登陆-校验是否登陆
  static loginTokenCheck(String token) async {
    return await fetch('/login/token-check',
        method: 'POST', data: {"token": token});
  }

  /// ------
  /// 用户管理
  /// ------

  /// 用户管理-查询用户详情
  static userQueryById(String id) async {
    return await fetch('/user/queryById?id=$id', method: 'GET');
  }

  /// 用户管理-修改密码
  static userUpdatePassword(
      {required String phone,
      required String newWord,
      required String old,
      required String repeat}) async {
    return await fetch('/user/updatePassword', method: 'POST', data: {
      "phone": phone,
      "newWord": newWord,
      "old": old,
      "repeat": repeat
    });
  }

  /// 用户管理-修改手机
  static userUpdatePhone(
      {required String phone,
      required String newWord,
      required String old,
      required String repeat}) async {
    return await fetch('/user/updatePhone', method: 'POST', data: {
      "phone": phone,
      "newWord": newWord,
      "old": old,
      "repeat": repeat
    });
  }

  /// ------
  /// 偏载信息
  /// ------

  /// 偏载信息-信息录入
  static shippingInputRecord(
      {required String containerNum,
      required String templateNum,
      required String userId}) async {
    return await fetch('/shipping/inputRecord', method: 'POST', data: {
      "containerNum": containerNum,
      "templateNum": templateNum,
      "userId": userId
    });
  }

  /// 偏载信息-运输结束
  static shippingFinish(String userId) async {
    return await fetch('/shipping/finish?userId=$userId', method: 'GET');
  }

  /// 偏载信息-选择车板（列表数据）/shipping/queryCurrentRecord
  static shippingQueryCurrentRecord(String userId) async {
    return await fetch('/shipping/queryCurrentRecord?userId=$userId');
  }

  /// 偏载信息-车板详情
  static shippingQueryDetail(
      {required String templateNum, required String userId}) async {
    return await fetch(
        '/shipping/queryDetail?userId=$userId&templateNum=$templateNum',
        method: 'GET');
  }

  /// 偏载信息-删除记录 /shipping/remove
  static shippingRemove({required String id}) async {
    return await fetch('/shipping/remove?id=$id', method: 'GET');
  }

  static shippingTrigger({required String templateNum}) async {
    return await fetch('/shipping/trigger?templateNum=$templateNum', method: 'GET');
  }

  static baiduAccessToken() async {
    var controller = GetX.Get.find<GlobalController>();

    String url =
        "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${controller.appConfig.baiduOCRAPIKey}&client_secret=${controller.appConfig.baiduOCRAPISecret}";
    var response = await dio.request(url,
        options: Options(method: 'POST', headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }));
    print('baiduAccessToken response: $response');

    return response.data["access_token"];
  }

  /// 百度 api - 文字识别
  static baiduOcrAccurateBasic({required String image}) async {
    String token = await baiduAccessToken();

    String url =
        "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=$token";

    var response = await dio.request(url,
        options: Options(
            method: 'POST',
            headers: {"Content-Type": "application/x-www-form-urlencoded"}),
        data: FormData.fromMap({
          'image': image,
        }));

    print('baiduOcrAccurateBasic response: $response');

    return response.data;
  }

  static Future<dynamic> fetch(String url,
      {String method = "GET", data}) async {
    String? token = await DBService.getData(DBKey.userToken);
    var response = await dio.request(buildPath(url),
        options: Options(method: method, headers: {'token': token}),
        data: jsonEncode(data));

    print(
        'api fetch!: \n -token: $token \n -请求: url: $url data: $data \n -response: ${response.data}');

    if (response.statusCode == 200 && response.data["code"] == '200') {
      // 成功
      return response.data["result"] ?? {};
    } else if (response.data["code"] == '500') {
      Dialogs.showFailed(title: "出错了", body: response.data["desc"]);
      return null;
    } else {
      // 请求失败 TODO 弹窗
      Dialogs.showFailed(title: "未知异常", body: '$response');
      return null;
    }
  }

  static String buildPath(String uri) {
    var controller = GetX.Get.find<GlobalController>();
    return controller.appConfig.serviceDomain + uri;
  }
}
